<template>
  <div class="app-container">
    <div class="page-card" v-if="pageData.length !== 0">
      <el-tabs v-model="activeNameKey" @tab-click="handleClickSubject">
        <el-tab-pane
          v-for="item in pageData"
          :label="item.name"
          :name="String(item.id)"
          :key="item.id"
        >
        </el-tab-pane>
      </el-tabs>
      <el-tabs
        v-if="pageData.length !== 0"
        v-model="activeNamechildrenKey"
        @tab-click="handleClick"
        :lazy="true"
      >
        <el-tab-pane
          label="评阅进度"
          v-if="$auth.hasRole('admin')"
          name="pyjd"
        ></el-tab-pane>
        <el-tab-pane label="评阅详情" name="pyxq" v-if="activeNameKey !== '-1'"></el-tab-pane>

        <el-tab-pane
          label="评阅概览"
          v-if="$auth.hasRole('admin') && activeNameKey !== '-1'"
          name="pygl"
        ></el-tab-pane>
        <el-tab-pane v-if="activeNameKey!='-1'"
          :label="'上次更新时间：' + (refreshTime ? refreshTime : '-')"
          name="znyj"
          disabled
          style="color: red !important"
        ></el-tab-pane>
      </el-tabs>
      <component
        v-if="pageData.length !== 0 && xmxx.id"
        :key="`component-${activeNameKeyValue}`"
        :subjectId="activeNameKey"
        :xmxx="xmxx"
        :subjectName="
          pageData
            ? pageData.filter((item) => item.id == activeNameKey)[0]
              ? pageData.filter((item) => item.id == activeNameKey)[0].name
              : ''
            : ''
        "
        :is="
          activeNamechildrenKey == 'pyjd' && activeNameKey == '-1'
            ? 'qbjd'
            : activeComponents
        "
      ></component>
    </div>
    <div class="page-card" v-else>
      <el-empty description="暂无数据"></el-empty>
    </div>
  </div>
</template>

<script>
import { grouplist } from "@/api/jcgl/xkgl";
import { subjectlistselect } from "@/api/common";
import { exammainEdit } from "@/api/xmgl";
import { getSubjectList, statistics, getRefreshTime } from "@/api/xmgl/pyjd";
// import csxx from "./csxx.vue";
// import ksgl from "./ksgl.vue";
// import pyjsgl from "./pyjsgl.vue";
// import xsgl from "./xsgl.vue";

import pyjd from "./pyjd.vue";
import pyxq from "./pyxq.vue";
import pygl from "./pygl.vue";
import qbjd from "./qbjd.vue";
export default {
  name: "Project_pyjd",
  components: {
    // ksgl,
    // csxx,
    // pyjsgl,
    // xsgl,

    pyjd,
    pyxq,
    pygl,
    qbjd,
  },

  dicts: ["grade", "type", "mode"],
  data() {
    return {
      refreshTime: undefined,
      pageData: [],

      loading: false,
      xmxx: {},
      activeComponentsValue: "",
      activeComponents: "",
      activeName: "",
      subjectName: "",

      activeNamechildrenKey:"pyjd",
      activeComponents: "",

      editKmVisible: false,
      editForm: {
        examName: "",
        examTime: null,
        grade: "",
        examType: "",
        projectMode: "",
        selectType: "",
        // examSubjectList: [],
      },
      rules: {
        examName: [
          { required: true, message: "项目名称不能为空", trigger: "change" },
        ],
        examTime: [
          { required: true, message: "项目时间不能为空", trigger: "change" },
        ],
        grade: [
          { required: true, message: "所属年级不能为空", trigger: "change" },
        ],
        examType: [
          { required: true, message: "项目类型不能为空", trigger: "blur" },
        ],
        projectMode: [
          { required: true, message: "项目模式不能为空", trigger: "change" },
        ],
        selectType: [
          { required: true, message: "选科类型不能为空", trigger: "change" },
        ],
        // examSubjectList: [
        //   { required: true, message: "考试不能为空", trigger: "change" },
        // ],
      },

      xklxlb: [],
      qbxklb: [],
      firstRemoved: false, // 是否已删掉第一个
      rawPageData: [],

      activeNameKeyValue:"",
      activeNameKey:'-1'
    };
  },

  computed: {
    // xklb() {
    //   let xklb = [];
    //   if (this.xmxx.selectType && this.xklxlb.length > 0) {
    //     let obj = this.xklxlb.filter((item) => {
    //       return this.xmxx.selectType == item.id;
    //     })[0];
    //     let examSubjects = obj.examSubjects.split(",");
    //     let basicChooseSubject;
    //     if (obj.basicChooseSubject) {
    //       basicChooseSubject = obj.basicChooseSubject.map((item) => {
    //         return item.selectSubjectIds.split(",");
    //       });
    //       basicChooseSubject = basicChooseSubject.reduce((acc, curr) => {
    //         return acc.concat(curr);
    //       }, []);
    //       examSubjects = examSubjects.concat(basicChooseSubject);
    //     }
    //     this.qbxklb.map((item) => {
    //       if (examSubjects.indexOf(item.subjectId.toString()) != -1) {
    //         xklb.push(item);
    //       }
    //     });
    //   }
    //   return xklb;
    // },
  },
  watch: {
    activeNamechildrenKey: {
      handler(newVal, oldVal) {
        this.activeComponents = newVal;
      },
      immediate: true,
    },

    activeComponents: {
      handler(newVal, oldVal) {
        console.log(newVal, "dddddd");
        // this.getRefreshTime();
      },
      deep: true,

      // immediate:true
    },
  },
  async mounted() {},
  async created() {
    await this.$store.dispatch("getXmxx").then((res) => {
      this.xmxx = res;
      this.getExamList();
    });
    // grouplist({ pageNum: 1, pageSize: 9999 }).then((res) => {
    //   this.xklxlb = res.rows;
    // });
    // subjectlistselect("-1").then((res) => {
    //   this.qbxklb = res.data;
    // });
  },
  methods: {

    getExamList() {
      console.log(this.xmxx, "this.xmxx");
      const init = (data) => {
        this.rawPageData = [{ name: "全部", id: "-1" }, ...data];
        this.activeNameKey = String(this.rawPageData[0]?.id) || undefined;
        this.subjectName = this.rawPageData[0]?.name || undefined;
        this.pageData = this.rawPageData;
      };

      if (
        this.$auth.hasRole("admin") ||
        this.$auth.hasExamPermi("reviewing:teachers:pyxq")
      ) {
        getSubjectList({ examId: this.xmxx.id }).then((res) => {
          init(res.rows);
        });
      } else if (this.$auth.hasExamPermi("reviewing:teachers:pyxqkm")) {
        init(
          this.$store.state.xmgl.examSubjects.map((item) => {
            return {
              ...item,
              id: item.examSubjectId,
              name: item.examSubjectName,
            };
          })
        );
      }
    },
    // 学科tab切换
    handleClickSubject(e, t) {
      // this.activeNamechildrenKey = "pyjd";
      if (e.name == '-1') {
        this.activeNamechildrenKey = 'pyjd';
      }
      this.activeNameKey = e.name;
      this.activeNameKeyValue = new Date();
      getRefreshTime({ examId: this.activeNameKey }).then((res) => {
        this.refreshTime = res.msg;
      });
    },
    handleClick(tab, event) {
      // 不删除全部tab，改为隐藏评阅详情和评阅概览
      // if (tab.name !== "pyjd") {
      //   if (!this.firstRemoved) {
      //     this.pageData = this.rawPageData.slice(1); // 砍掉第一个
      //     this.firstRemoved = true;
      //   }
      // } else {
      //   this.pageData = this.rawPageData; // 恢复原始数据
      //   this.firstRemoved = false;
      // }
      // 3. 无论哪种情况，都重新取当前第一项作为默认值
      if (this.pageData[0].id !== -1 && this.activeNameKey==-1) {
      this.activeNameKey = String(this.pageData[0]?.id) || undefined;
      this.subjectName = this.pageData[0]?.name || undefined;
      this.activeNamechildrenKey = tab.name;
      }
    },

    edit() {
      let row = this.xmxx;
      this.editForm.id = row.id;
      this.editForm.examName = row.examName;
      this.editForm.examTime = [row.startTime, row.endTime];
      this.editForm.examType = row.examType;
      this.editForm.projectMode = row.projectMode;
      this.editForm.selectType = row.selectType.toString();

      this.editForm.grade = row.grade;
      // this.editForm.examSubjectList = row.examSubjectList.map((item) => {
      //   return item.subjectId;
      // });

      this.editKmVisible = true;
    },

    beforeClose(done) {
      this.editForm = {
        examName: "",
        examTime: null,
        grade: "",
        examType: "",
        projectMode: "",
        selectType: "",
        // examSubjectList: [],
      };
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate();
        done();
      });
    },
    handleClose() {
      this.beforeClose(() => {
        this.editKmVisible = false;
      });
    },

    editSubmit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          let req = exammainEdit;
          let data = {
            ...this.editForm,
            grade: this.editForm.grade,
            projectType: this.editForm.examType,
          };

          data.startTime = data.examTime[0];
          data.endTime = data.examTime[1];
          // data.examSubjectList = data.examSubjectList.map((item) => {
          //   let xklbFilter = this.xklb.filter((v) => {
          //     return v.subjectId == item;
          //   })[0];

          //   return {
          //     subjectId: xklbFilter.subjectId,
          //     subjectName: xklbFilter.subjectName,
          //   };
          // });
          req(data)
            .then((res) => {
              this.$modal.msgSuccess("操作成功");
              let xmxx = {
                ...this.xmxx,
                examName: data.examName,
                startTime: data.startTime,
                endTime: data.endTime,
                grade: data.grade,
                examType: data.examType,
                projectMode: data.projectMode,
              };
              this.xmxx = xmxx;
              this.$store.dispatch("setXmxx", xmxx).then(() => {
                this.handleClose();
              });
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.editKmVisible {
  .el-input,
  .el-cascader,
  .el-select {
    width: 100%;
  }
}
.page-card {
  & + .page-card {
    margin-top: 14px;
  }
}
.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;

  .header-info {
    display: flex;
    align-items: center;

    p {
      padding: 0 15px;
      border-left: 1px solid #ddd;

      &:first-child {
        padding-left: 0;
        border-left: none;
      }

      span {
        color: rgb(144, 147, 153);
      }
    }
  }
}
</style>
<style scoped>
>>> .is-disabled {
  color: red !important;
}
</style>